package com.coffee.test.util;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class SyncZebraFuture  implements Future<String> {

    private final CountDownLatch latch = new CountDownLatch(1);
    private String command;
    private final long beginTime = System.currentTimeMillis();

    public SyncZebraFuture() {
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return command != null;
    }

    @Override
    public String get() throws InterruptedException {
        latch.await();
        return this.command;
    }

    // 获取响应结果，直到有结果或者超过指定时间就返回。
    @Override
    public String get(long timeout, TimeUnit unit) throws InterruptedException {
        if (latch.await(timeout, unit)) {
            return this.command;
        }
        return null;
    }

    // 用于设置响应结果，并且做countDown操作，通知请求线程
    public void setResponse(String response) {
        this.command = response;
        latch.countDown();
    }

    public long getBeginTime() {
        return beginTime;
    }
}